/*
   Copyright 2009 the original author or authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.googlecode.kohmori.springmvc;

import java.util.Map;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;

public class ReportNameHandlerMapping extends AbstractHandlerMapping 
        implements InitializingBean {

    private String reportName;
    private String requiredServletPath = null;
    private final Map<String, Object> reportMappings = new HashMap<String, Object>();
    
    public final void setRequiredServletPath(String servletPath) {
        this.requiredServletPath = servletPath;
    }

    public final void setReportMappings(Map<String, Object> paramMappings) {
        this.reportMappings.putAll(paramMappings);
    }
    
    public final void setReportName(String parameterName) {
        this.reportName = parameterName;
    }  
    
    public void afterPropertiesSet() throws Exception {
        if (reportName == null || reportName.trim().equals("")) {
            throw new IllegalStateException("Report Name is missing.");
        }
    }

    @Override
    protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
        if (requiredServletPath == null || requiredServletPath.equals(
                request.getServletPath())) {
            String desiredReport = request.getParameter(reportName);
            return reportMappings.get(desiredReport);
        } else {
            return null;
        }
    }
    
}